package service

import (
	"bytes"
	"encoding/json"
	"harbor/src/configs"
	"harbor/src/models"
	"io/ioutil"
	"strconv"
)
//查询项目中的所有成员及权限及推送
func CheckUserInProject(projects []models.Proj,user models.User,oldharbor_api string,
	newharobr_api string,Newuser models.User){
	UserRole:=make([]*models.Member,0)
	//遍历所有项目，拿到项目的成员列表
	for _,project:=range projects{
		client:=configs.HttpInit()
		resp,err:=client.Get("https://"+user.
			UserName+":"+user.Password+"@"+oldharbor_api+
			"/api/projects/"+strconv.Itoa(project.Id)+"/members/")
		if err!=nil{
			panic(err)
		}
		body,err:= ioutil.ReadAll(resp.Body)
		if err!=nil{
			panic(err)
		}
		json.Unmarshal(body,&UserRole)
		//fmt.Println(string(body))
		for _,UserMember:=range UserRole{
			CretUserforProject(Newuser,newharobr_api,UserMember,project)
		//	fmt.Println(UserMember)
		}
	}
}
//为项目添加成员
func CretUserforProject(user models.User,harborurl string,member *models.Member,proj models.Proj) {
	type User struct {
		Role_id int `json:"role_id""`
		Member_user map[string]string  `json:"member_user"`
	}
	var project_creat User
	project_creat = User{
		Role_id: member.Role_Id,
		Member_user: map[string]string{
			"username":member.Entity_Name,
		},
	}
	user_role,err:=json.Marshal(project_creat)
	if err!=nil{
		panic(err)
		return
	}
	read:=bytes.NewReader(user_role)

	resp1, _ := configs.HttpInit().Get("https://"+harborurl+"/api/projects")
	body1, _ := ioutil.ReadAll(resp1.Body)
	defer resp1.Body.Close()
	//所有项目
	var harbor_proj_arr []models.Proj
	json.Unmarshal(body1, &harbor_proj_arr)
	for _,newprojet:=range harbor_proj_arr {
		if newprojet.Name==proj.Name{
			resp, _ := configs.HttpInit().Post("https://"+user.UserName+":"+
				user.Password+"@"+harborurl+"/api/projects/"+strconv.Itoa(newprojet.Id)+"/members/",
				"application/json",read)

			_,err := ioutil.ReadAll(resp.Body)
			if err!=nil{
				panic(err)
			}
			defer resp.Body.Close()
		}
	}



}